﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using NTQOnlineExam.Services.Infrastructure;
using NTQOnlineExam.Services.Models;

namespace NTQOnlineExam.Services.DBCommand.Examination
{
    public class GetExamInfoByTermIdDbCommand : ICommand<IList<ExamInformationDTO>>
    {
        private readonly int _termId;

        public GetExamInfoByTermIdDbCommand(int termId)
        {
            _termId = termId;
        }

        public IList<ExamInformationDTO> Execute()
        {
            var connectionString = ConfigurationSettings.AppSettings["ConnectionString"];
            var dt = new DataTable();
            using (var con = new SqlConnection(connectionString))
            {
                using (var cmd = new SqlCommand("[GetExamInformation]", con))
                {
                    var adapt = new SqlDataAdapter(cmd);
                    adapt.SelectCommand.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@TermId", SqlDbType.Int).Value = _termId;
                    con.Open();
                    adapt.Fill(dt);
                    cmd.ExecuteNonQuery();
                }
                return GetExamInformationDtos(dt);
            }
        }

        private IList<ExamInformationDTO> GetExamInformationDtos(DataTable dtTable)
        {
            return (from DataRow dtRow in dtTable.Rows
                    select new ExamInformationDTO
                    {
                        SectionId = (int)dtRow["SectionId"],
                        SectionName = dtRow["SectionName"].ToString(),
                        TotalQuestion = (int)dtRow["TotalQuestion"]
                    }).ToList();
        }
    }
}
